// pages/new/new.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    name: '',
    windowHeight: 0,
    windowWidth: 0,
    query: [{
      q_id: 111,
      title: "问卷1",
    }],
    UrlList: [
      '/pages/radioOption/radio',
      '/pages/checkBox/checkbox',
      '/pages/InputOption/InputOption'
    ],
    codeSrc: '',
    haveGetCodeSrc: false,
    questions: []
  },
  titleInput(e) {
    this.setData({
      name: e.detail.value
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const scene = decodeURIComponent(options.scene);
    console.log(scene);
    console.log("onLoad!")
  },
  uuid() {
    var s = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
      s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[4] = s[9] = s[14] = s[19] = "-";
    
    var uuid = s.join("");
    return uuid.substring(0,24);
  },
  Submit() {
    if (this.data.name == '' || this.data.name == null) {
      wx.showToast({
        title: '请输入问卷标题！',
        icon: 'none',
        duration: 1500
      })
      return;
    }
    if (this.data.questions.length == 0 || this.data.questions == null) {
      wx.showToast({
        title: '请至少输入一个题目！',
        icon: 'none',
        duration: 1500
      })
      return;
    }
    var i = 0;
    for (var item in this.data.questions) {
      try{
        delete this.data.questions[i].__webviewId__;
      }
      catch(e){
      }
      try{
        delete this.data.questions[i].charCode;
      }
      catch(e){

      }
      console.log(this.data);
      this.data.questions[i].id = i + 1;
      if (this.data.questions[i].type == "input"&&this.data.questions[i].options!=null) {
        try{
          delete this.data.questions[i].options;
        }
        catch(e){
        }
      }
      i = i + 1;
    }
    console.log("uuid:");
    var uuid = this.uuid();
    this.data.uuid=uuid;
    
    this.setData({
      uuid: uuid
    })
    this.showAction();
    console.log(uuid);

    var new_data = {};
    new_data.name = this.data.name;
    new_data.q_id = uuid;
    new_data.questions = this.data.questions;
    const db = wx.cloud.database({})
    db.collection('questions').add({
      data: new_data,
      success: res => {
        wx.showToast({
          title: '新增记录成功',
        })
        console.log('[数据库] [新增记录] 成功，记录 _id: ', res._id)
        this.data.questions._id = res._id;
      },
      fail: err => {
        wx.showToast({
          icon: 'none',
          title: '新增记录失败'
        })
        console.error('[数据库] [新增记录] 失败：', err)
      }
    })
  },

  newInput() {
    var that = this.data;
    wx.showActionSheet({
      itemList: ['单选题', '多选题', '填空题'],
      itemColor: '#007aff',
      success(res) {
        if (res.tapIndex === 0) {
          wx.navigateTo({
            url: that.UrlList[res.tapIndex]
          })
        } else if (res.tapIndex === 1) {
          wx.navigateTo({
            url: that.UrlList[res.tapIndex]
          })
        } else if (res.tapIndex === 2) {
          wx.navigateTo({
            url: that.UrlList[res.tapIndex]
          })
        }
      }
    })
  },
  newChoose() {
    var data = {
      pos: 1,
      title: "姓名",
      type: 'input',
      input_type: 'text',
    };
    this.add(data)
  },
  toEdit() {
    wx.navigateTo({
      url: '../edit/edit'
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    wx.getSystemInfo({
      success: res => {
        this.setData({
          windowWidth: res.windowWidth,
          windowHeight: res.windowHeight
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var app = getApp();
    console.log(app.globalData);
    app.globalData.qqq = 3;
    //if(index.setData(3));
    console.log(app.globalData.tmpquestion);
    console.log(this.data.questions);
    if (app.globalData.edited == true) {
      this.add(app.globalData.tmpquestion);
    }
    app.globalData.edited = false;
    console.log(this.data.questions);
  },
  add(data) {
    this.data.questions.push(data);
    var newquestions = this.data.questions;
    this.setData({
      questions: newquestions
    });
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    console.console.log("????????");
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},

  getCodeSrc() {
    wx.showLoading({
      title: '',
    });
    wx.cloud.callFunction({
      name: 'quickstartFunctions',
      config: {
        env: this.data.envId
      },
      data: {
        type: 'getMiniProgramCode',
        code: this.data.uuid,
      }
    }).then((resp) => {
      console.log(this.data.codeSrc);
      this.setData({
        haveGetCodeSrc: true,
        codeSrc: resp.result
      });
      wx.hideLoading();
    }).catch((e) => {
      console.log(e);
      this.setData({
        showUploadTip: true
      });
      wx.hideLoading();
    });
  },
  toAnswer() {
    wx.navigateTo({
      url: '../AnswerSheet/AnswerSheet'
    })
  },
  showAction: function () {
    this.getCodeSrc();
    console.log(this.data.codeSrc);
    wx.downloadFile({
      url: this.data.codeSrc,
      success: function (res) {
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success:function(dres){
            console.log(dres);
            console.log("saved!!")
          },
          fail(e)
          {
            console.log(e);
          }
        })
      },
      fail(e)
          {
            console.log(e);
          }
    })
    this.setData({
      modalHidden: false,
    })
    console.log(this.data.modalHidden);
  },

  modalCandel: function () {
    // do something
    this.setData({
      modalHidden: true,
    })
  },

  modalConfirm: function () {
    // do somethings
    this.setData({
      modalHidden: true,
    })
  },
  // 跳转函数
 
  

  copyCode: function() {
    wx.setClipboardData({
      data:this.data.uuid,
      success: function () {
        wx.showToast({
          title: '复制成功',
        })
      }
    })
  },
})